package org.mikhaylov.cp.service.command.impl;

import javax.servlet.http.HttpServletRequest;

import org.mikhaylov.cp.service.command.ServiceCommand;
import org.mikhaylov.cp.service.db.entities.City;
import org.mikhaylov.cp.service.db.entities.User;
import org.mikhaylov.cp.service.hibernate.HibernateManager;
import org.mikhaylov.cp.service.response.ResponseType;

public class RegisterServiceCommand extends ServiceCommand {

	private static final long serialVersionUID = -4454224887680694962L;
	private String login = null;
	private String password = null;
	private String passwordRepeat = null;
	private City city = null;

	@Override
	protected boolean checkParams(HttpServletRequest request) {
		if (request.getAttribute("login") == null
				|| request.getAttribute("password") == null
				|| request.getAttribute("passwordRepeat") == null
				|| request.getAttribute("city") == null
				|| !(request.getAttribute("login") instanceof String)
				|| !(request.getAttribute("password") instanceof String)
				|| !(request.getAttribute("passwordRepeat") instanceof String)
				|| !(request.getAttribute("city") instanceof String)
				|| ((String) request.getAttribute("login")).isEmpty()
				|| ((String) request.getAttribute("password")).isEmpty()
				|| ((String) request.getAttribute("passwordRepeat")).isEmpty()
				|| ((String) request.getAttribute("city")).isEmpty()) {
			response.setType(ResponseType.ERROR);
			response.setMeta("Wrong parameters");
			return false;
		}
		return true;
	}

	@Override
	protected boolean extractParams(HttpServletRequest request) {
		login = String.valueOf(request.getAttribute("login"));
		password = String.valueOf(request.getAttribute("password"));
		passwordRepeat = String.valueOf(request.getAttribute("passwordRepeat"));
		city = HibernateManager.getInstance().getCity(
				String.valueOf(request.getAttribute("city")));

		if (!password.equals(passwordRepeat)) {
			response.setType(ResponseType.ERROR);
			response.setMeta("Passwords do not match");
			return false;
		}
		
		if (city == null) {
			response.setType(ResponseType.ERROR);
			response.setMeta("Bad city");
			return false;
		}
		
		return true;
	}

	@Override
	protected void process(HttpServletRequest request) {
		User user = new User();
		user.setLogin(login);
		user.setPassword(password);
		user.setBalance(0.);
		user.setCity(city);
		user.setName("");
		user.setDesc("");
		user.setPhone("");

		if (!HibernateManager.getInstance().addUser(user)) {
			response.setType(ResponseType.ERROR);
			response.setMeta("User already exists");
			return;
		}

		request.setAttribute("user", user);
		response.setType(ResponseType.SUCCESS);
		response.setMeta("You have been successfully registered");
	}

}
